package com.hans.scala

/**
  * 偏应用函数
  *
  */
object PartiallyAppliedFunctionExample {
  def main(args: Array[String]) {
    //    def sum(a: Int, b: Int, c: Int) = a + b + c
    //    println(sum(1, 3, 4))
    //    val a = sum _
    //
    //    println(a(1, 3, 4))
    //    println(a.apply(1, 3, 4))
    //
    //    val b = sum(1, _: Int, 4)
    //    println(b(3))

    val someNumbers = List(-3, 34, -23, 3, 2, 10, 5)
    /**
      *
      */
    var s = 0
    //    someNumbers.foreach((x: Int) => s += x) //闭包
    someNumbers.foreach(s += _)
    println(s)
    /**
      * 简化代码
      */
    //        println(someNumbers.foreach((x: Int) => println(x)))
    //    println(someNumbers.foreach(x => println(x)))
    //    println(someNumbers.foreach(println _))
    //        println(someNumbers.foreach(println))

    println(someNumbers.filter((x: Int) => x > 5))
    println(someNumbers.filter(x => x > 5))
    println(someNumbers.filter(_ > 5))

    val one: PartialFunction[Int, String] = {
      case 1 => "one"
    }
    val two: PartialFunction[Int, String] = {
      case 2 => "two"
    }
    val three: PartialFunction[Int, String] = {
      case 3 => "three"
    }
    val wildcard: PartialFunction[Int, String] = {
      case _ => "something else"
    }
    val partial = one orElse two orElse three orElse wildcard

    partial(5)
  }
}
